package com.example.hello.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.hello.dto.EmployeeAddDTO;
import com.example.hello.dto.EmployeeQueryDTO;
import com.example.hello.dto.EmployeeUpdateDTO;
import com.example.hello.dto.WorkExperienceDTO;
import com.example.hello.entity.Department;
import com.example.hello.entity.Employee;
import com.example.hello.entity.Position;
import com.example.hello.entity.WorkExperience;
import com.example.hello.exception.BusinessException;
import com.example.hello.mapper.DepartmentMapper;
import com.example.hello.mapper.EmployeeMapper;
import com.example.hello.mapper.PositionMapper;
import com.example.hello.mapper.WorkExperienceMapper;
import com.example.hello.service.EmployeeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class EmployeeServiceImpl implements EmployeeService {
    
    private final EmployeeMapper employeeMapper;
    private final DepartmentMapper departmentMapper;
    private final PositionMapper positionMapper;
    private final WorkExperienceMapper workExperienceMapper;

    @Override
    public IPage<Employee> listEmployees(EmployeeQueryDTO queryDTO) {
        try {
            Page<Employee> page = new Page<>(queryDTO.getPage(), queryDTO.getPageSize());
            return employeeMapper.selectEmployeeList(page, queryDTO);
        } catch (Exception e) {
            log.error("查询员工列表失败", e);
            throw new BusinessException("查询员工列表失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Employee addEmployee(EmployeeAddDTO addDTO) {
        // 检查用户名是否已存在
        if (isUsernameExists(addDTO.getUsername())) {
            throw new BusinessException("用户名已存在");
        }
        
        Employee employee = new Employee();
        employee.setUsername(addDTO.getUsername());  // 使用 username 而不是 name
        employee.setGender(addDTO.getGender());
        employee.setPhoneNumber(addDTO.getPhoneNumber());
        employee.setDepartmentId(addDTO.getDepartmentId());
        employee.setPositionId(addDTO.getPositionId());
        employee.setAvatar(addDTO.getAvatar());
        employee.setJoinDate(addDTO.getJoinDate());
        
        // 设置默认密码
        employee.setPassword(AuthServiceImpl.encryptPassword("123456"));
        
        employeeMapper.insert(employee);
        return employee;
    }

    @Override
    @Transactional
    public void updateEmployee(Integer id, EmployeeUpdateDTO updateDTO) {
        Employee employee = employeeMapper.selectById(id);
        if (employee == null) {
            throw new BusinessException("员工不存在");
        }
        
        // 验证部门是否存在
        if (updateDTO.getDepartmentId() != null) {
            Department department = departmentMapper.selectById(updateDTO.getDepartmentId());
            if (department == null) {
                throw new BusinessException("部门不存在");
            }
            employee.setDepartmentId(updateDTO.getDepartmentId());
        }
        
        // 验证职位是否存在
        if (updateDTO.getPositionId() != null) {
            Position position = positionMapper.selectById(updateDTO.getPositionId());
            if (position == null) {
                throw new BusinessException("职位不存在");
            }
            employee.setPositionId(updateDTO.getPositionId());
        }
        
        // 更新其他字段
        if (updateDTO.getUsername() != null) {
            employee.setUsername(updateDTO.getUsername());
        }
        if (updateDTO.getGender() != null) {
            employee.setGender(updateDTO.getGender());
        }
        if (updateDTO.getPhoneNumber() != null) {
            employee.setPhoneNumber(updateDTO.getPhoneNumber());
        }
        if (updateDTO.getAvatar() != null) {
            employee.setAvatar(updateDTO.getAvatar());
        }
        
        // 设置更新时间
        employee.setUpdateTime(LocalDateTime.now());
        
        employeeMapper.updateById(employee);
        
        // 重新查询并填充关联信息
        fillEmployeeInfo(employee);
    }

    @Override
    @Transactional
    public Integer deleteEmployees(List<Integer> ids) {
        employeeMapper.deleteBatchIds(ids);
        return 0;  // 不再返回工作经历数量
    }

    private boolean isUsernameExists(String username) {
        Long count = employeeMapper.selectCount(
            new QueryWrapper<Employee>().eq("username", username)
        );
        return count > 0;
    }
    
    private void fillEmployeeInfo(Employee employee) {
        if (employee.getDepartmentId() != null) {
            employee.setDepartment(departmentMapper.selectById(employee.getDepartmentId()));
        }
        if (employee.getPositionId() != null) {
            employee.setPosition(positionMapper.selectById(employee.getPositionId()));
        }
    }
} 